package com.wu.service.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.wu.common.page.PageResult;
import com.wu.common.service.impl.BaseServiceImpl;
import com.wu.dao.sys.dao.SysDictDataDao;
import com.wu.entity.sys.SysDictDataEntity;
import com.wu.dao.sys.vo.SysDictDataVO;
import com.wu.service.sys.convert.SysDictDataConvert;
import com.wu.service.sys.query.SysDictDataQuery;
import com.wu.service.sys.service.SysDictDataService;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 数据字典
 *
 * @author wzd 
 */
@Service
@AllArgsConstructor
public class SysDictDataServiceImpl extends BaseServiceImpl<SysDictDataDao, SysDictDataEntity> implements SysDictDataService {

    @Override
    public PageResult<SysDictDataVO> page(SysDictDataQuery query) {
        IPage<SysDictDataEntity> page = baseMapper.selectPage(getPage(query), getWrapper(query));
        List<SysDictDataVO> list  = new ArrayList<>();

        page.getRecords().forEach(item -> {
            SysDictDataVO vo = new SysDictDataVO();
            BeanUtils.copyProperties(item, vo);
            list.add(vo);
        });
        return new PageResult<>(list, page.getTotal());
    }

    private Wrapper<SysDictDataEntity> getWrapper(SysDictDataQuery query){
        LambdaQueryWrapper<SysDictDataEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDictDataEntity::getDictTypeId, query.getDictTypeId());
        wrapper.orderByAsc(SysDictDataEntity::getSort);

        return wrapper;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(SysDictDataVO vo) {

        SysDictDataEntity entity = new SysDictDataEntity();
        BeanUtils.copyProperties(vo,entity);
        baseMapper.insert(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SysDictDataVO vo) {
        SysDictDataEntity entity = SysDictDataConvert.INSTANCE.convert(vo);

        updateById(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<Long> idList) {
        removeByIds(idList);
    }

}